package com.TEAM6.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("*.zzang")
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Forward forward = null;
	public FrontController() {
		super();

	}

	protected void doProcess(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		String RequestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = RequestURI.substring(contextPath.length()+5);
		System.out.println(command);

		Action action = null;
		
		
		if (command.equals("joinForm.zzang")) {
			forward = new Forward();
			forward.setRedirect(true);
			forward.setPagePath("./JoinForm.jsp");
		}else if (command.equals("login.zzang")) {
			action = new LoginAction();
			try {
				forward = action.execute(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if(command.equals("search.zzang")){
			if (isSession(request)) {
				action = new SearchAction();
				try {
					forward = action.execute(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else{ forward = isForward(forward);
			}
		}
		else if (command.equals("main.zzang")) {
			if (isSession(request)) {
				action = new MainAction();
				try {
					forward = action.execute(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else{ forward = isForward(forward);}
		}	
    	

		if (forward != null) {
			if (forward.isRedirect()) {
				response.sendRedirect(forward.getPagePath());
			} else {
				RequestDispatcher dispatcher = 
    					request.getRequestDispatcher(
    							forward.getPagePath());
				dispatcher.forward(request, response);
			}
		}
	}

	protected boolean isSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		boolean check = false;
		if (session.getAttribute("id") != null) {
			check = true;
		}
		return check;
	}

	protected Forward isForward(Forward forward) {
		forward = new Forward();
		forward.setRedirect(true);
		forward.setPagePath("./index.jsp");

		return forward;
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		doProcess(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		doProcess(request, response);
	}

}
